<template>
  <div login-component class="login">
    <div class="title">登录系统</div>
    <input type="text" class="login-input" placeholder="用户名" v-model="account" />
    <input type="password" class="login-input" placeholder="密码" v-model="password" />
    <button :disabled="disabled" @click="onLoginClicked">{{loginText}}</button>
  </div>
</template>

<script>
import api from "../../services/auth.api";
import _ from "../../libs/utils";

export default {
  data() {
    return {
      account: "admin",
      password: "123qwe",
      state: "waiting"
    };
  },
  computed: {
    loginText() {
      return this.state == "processing" ? "正在登录" : "登录";
    },
    disabled() {
      return (
        this.account === "" ||
        this.password === "" ||
        this.state === "processing"
      );
    }
  },
  methods: {
    onLoginClicked() {
      this.state = "processing";
      api
        .login(this.account, this.password)
        .then(d => {
          this.state = "waiting";
          if (d.stat === "ok") {
            this.$router.push("/anouce");
          } else {
            alert(d.stat);
          }
        })
        .catch(err => {
          this.state = "waiting";
          alert(err);
        });
    }
  },
  created: function() {
    var token = _.cookie.get("token");
    if (token && token != "") {
      this.status = "processing";
      api
        .getUserInfo()
        .then(d => {
          if (d.stat == "ok") this.$router.push("/anouce");
        })
        .catch(err => {
          this.status = "";
        });
    }
  }
};
</script>

<style scoped>
[login-component] {
  position: absolute;
  width: 200px;
  height: 150px;
  top: 50%;
  left: 50%;
  margin-top: -75px;
  margin-left: -100px;
  text-align: center;
}

.login .title {
  margin-bottom: 10px;
  font-size: 18px;
}

.login > input {
  width: 100%;
  height: 30px;
  padding: 5px;
  margin-bottom: 10px;
  outline: none;
  box-sizing: border-box;
}

.login > button {
  width: 100%;
  height: 30px;
  box-sizing: border-box;
}
</style>